package cn.lutu.security.security;

import cn.lutu.dao.mapper.UserMapper;
import cn.lutu.protocol.vo.UserLoginInfoVO;
import cn.lutu.util.exception.ServiceException;
import cn.lutu.util.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
   @Autowired
   private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        //通过用户输入的用户名从数据库中查询信息
        log.debug("Spring Security框架自动调用了UserDetailsService对象，将根据用户名获取用户详情，参数：{}", userName);
        UserLoginInfoVO userVO = userMapper.getLoginInfoByUsername(userName);
        log.info("根据用户名从数据库中查询用户详情，查询结果：{}",userVO);
        if (userVO == null){
            log.debug("开始处理用户名不存在的异常");
            String message = "用户名不存在，请重新输入！";
            log.info(message);
            throw new ServiceException(StatusCode.USERNAME_ERROR,message);
            }
//
        List<GrantedAuthority> authorities= new ArrayList<>();
        List<String> permissions = userVO.getPermissions();
        for (String permission: permissions
             ) {GrantedAuthority authority =new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }
        log.debug("权限列表为：{}",authorities);
        //创建自定义的UserDetails 并把后期需要用到的id和昵称保存到里面
        CustomUserDetails cud = new CustomUserDetails(userVO.getId(),userName,userVO.getPassword(),userVO.getNickName()
        ,userVO.getImgUrl(),authorities);
        log.info("认证结束，返回的CustomUserDetails为：{}",cud);
        return cud;
    }

}
